//
//  MallHomeViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/8/31.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "MallHomeViewController.h"
#import <XRCarouselView.h>
#import "MallsCollectionViewCell.h"
#import "AdsServer.h"
#import "Goods.h"
#import "MallClassificationViewController.h"
#import "MallDetailViewController.h"
#import "SearchViewController.h"
#import "MallClassViewController.h"
#import "MallShopCartViewController.h"
#import "MKJShoppingCartViewController.h"
#import "HomeCollectionViewHeaderView.h"
#import "MallListViewController.h"
#import "FullGate.h"
#import "MallBuyTogetherModel.h"
#import "NearbyShopViewController.h"

@interface MallHomeViewController () <UICollectionViewDelegate, UICollectionViewDataSource>

@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@end

@implementation MallHomeViewController {
    UIView          *_headBgView;
    UIButton        *_returnBtn;
    UIButton        *_shopCarBtn;
    UIButton        *_shopSpeciesBtn;
    XRCarouselView  *_carouselView;
    UIButton        *_recommendBtn;
    
    UICollectionView *_collectionView;
    MallsCollectionViewCell *_item;
    
    CGFloat         _collectionW;
    CGFloat         _collectionH;
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
	
}
- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
	
	
    [self GETMallsGoods];

    [self createUI];
    
    [self GETAds];
    
    [self refreshData];
}


#pragma mark ==========构建UI==========
- (void)createUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    _headBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, Height_NavBar)];
    [self.view addSubview:_headBgView];
    _headBgView.backgroundColor = UIMainColorRGB;
    
    // 附近商家
    UIButton *nearbyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headBgView addSubview:nearbyBtn];
    [nearbyBtn setBackgroundImage:IMAGE(@"job_nav_position") forState:UIControlStateNormal];
	[nearbyBtn setTintColor:kWhiteColor];
	//[nearbyBtn setTitle:@"附近" forState:UIControlStateNormal];
	nearbyBtn.titleLabel.font = [UIFont systemFontOfSize:12];
    [nearbyBtn addTarget:self action:@selector(nearbyShopBtnClick:) forControlEvents:UIControlEventTouchUpInside];
	if (IS_IPHONE_X || IS_IPHONE_Xs || IS_IPHONE_Xs_Max) {
		nearbyBtn.frame = CGRectMake(20, _headBgView.height/2-10, 16, 20);
		nearbyBtn.centerY = _headBgView.height/2+10;
	}
	else {
		nearbyBtn.frame = CGRectMake(20, _headBgView.height/2-15, 16, 20);
		nearbyBtn.centerY = _headBgView.height/2+10;
	}
    
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(44, 0, SCREEN_WIDTH-132, 30)];
    searchBar.centerY = nearbyBtn.centerY;
    searchBar.placeholder = @"请输入搜索内容…";
    searchBar.backgroundImage = IMAGE(@"clearImage");
    searchBar.layer.cornerRadius = searchBar.height/2;
    searchBar.layer.masksToBounds = YES;
    UIView *searchTextField = searchTextField = [searchBar valueForKey:@"_searchField"];
    searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
    [_headBgView addSubview:searchBar];
    
    UIView *searView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, searchBar.width, searchBar.height)];
    [searchBar addSubview:searView];
    [searView addTarget:self action:@selector(searchClicK:)];
    
    
    
    _shopCarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headBgView addSubview:_shopCarBtn];
    [_shopCarBtn setImage:IMAGE(@"icon_shopcar") forState:UIControlStateNormal];
    [_shopCarBtn addTarget:self action:@selector(cartClick:) forControlEvents:UIControlEventTouchUpInside];
    _shopCarBtn.frame = CGRectMake(SCREEN_WIDTH-88, 20, 44, 44);
	_shopCarBtn.centerY = nearbyBtn.centerY;
    
    _shopSpeciesBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_headBgView addSubview:_shopSpeciesBtn];
    [_shopSpeciesBtn setImage:IMAGE(@"icon_classify") forState:UIControlStateNormal];
    [_shopSpeciesBtn addTarget:self action:@selector(speciesClick:) forControlEvents:UIControlEventTouchUpInside];
    _shopSpeciesBtn.frame = CGRectMake(SCREEN_WIDTH-44, 20, 44, 44);
	_shopSpeciesBtn.centerY = nearbyBtn.centerY;
    
    
    _carouselView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SW(5)*2)];
    //    [_scrollView addSubview:_carouselView];
    _carouselView.contentMode = UIViewContentModeScaleAspectFill;
    _carouselView.imageArray = @[IMAGE(@"img.jpg")];
    _carouselView.time = 2;
    
    _recommendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_recommendBtn setImage:IMAGE(@"icon_recommend") forState:UIControlStateNormal];
    [_recommendBtn setTitle:@" 为你推荐" forState:UIControlStateNormal];
    _recommendBtn.titleLabel.font = kUHSystemFontWithSize(13);
    [_recommendBtn setTitleColor:kGrayColor forState:UIControlStateNormal];
    CGSize vipSize = [LZCTools textSizeWithText:_recommendBtn.titleLabel.text font:kUHSystemFontWithSize(13)];
    _recommendBtn.frame = CGRectMake(0, _carouselView.height, vipSize.width+5+SW(16), SW(12));
    _recommendBtn.centerX = self.view.centerX;
    
    // collectionView
    
    // 集合视图 collectionView所有布局的父类
    // 系统提供自带的布局类
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    // 默认为纵向滑动
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 10;
    flowLayout.minimumLineSpacing = 10;
    
    // 创建collectionView
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _headBgView.height, SCREEN_WIDTH, self.view.height-64) collectionViewLayout:flowLayout];
    [self.view addSubview:_collectionView];
    _collectionView.backgroundColor = UISeparatedColorRGB;
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    
    [_collectionView registerNib:[UINib nibWithNibName:@"MallsCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"item"];
    
    //flowLayout.headerReferenceSize = CGSizeMake(0, SW(5)*2+SW(12));
    //注册头视图
	/*
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader"];
	 */
	
	//头视图from yimei
	[_collectionView registerClass:[HomeCollectionViewHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HomeCollectionViewHeaderView"];
	
    CGSize size1 = [LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(12)];
    
    _collectionW = (SCREEN_WIDTH-30)/2;
    _collectionH = _collectionW+20+size1.height*3;
    
}

#pragma mark ==========UICollectionView==========
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    _item = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
	
	if (self.infoArr.count) {
		
		if (indexPath.section == 0) {
			FullGate *sup = self.infoArr[indexPath.section];
			MallBuyTogetherModel *model2 = [[MallBuyTogetherModel alloc] init];
			if (sup.goodss.count) {
				[model2 setValuesForKeysWithDictionary:sup.goodss[indexPath.row]];
			}
			_item.model2 = model2;
			
		}
		else
		{
			FullGate *sup = self.infoArr[indexPath.section];
			Goods *model = [[Goods alloc] init];
			if (sup.goodss.count) {
				[model setValuesForKeysWithDictionary:sup.goodss[indexPath.row]];
			}
			_item.model = model;
		}
		
	}
	
   // _item.model = self.infoArr[indexPath.row];
	
    return _item;
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
	return self.infoArr.count;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    //return self.infoArr.count;
	if (self.infoArr.count) {
		FullGate *model = self.infoArr[section];
		NSArray *arr = model.goodss;
		return arr.count;
	}
	else
		return 0;
}
//定义每个UICollectionView 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    //    NSLog(@"%f", _item.cover.height);
//    return CGSizeMake((SCREEN_WIDTH-30)/2, _item.money.y+_item.money.height+10);
    return CGSizeMake(_collectionW, _collectionH);
}
//定义每个UICollectionView 的 margin
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(10, 10, 10, 10);
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSLog(@"点击collectionView.item = %ld", indexPath.row);
	
	
	if (indexPath.section == 0) {
		FullGate *sup = self.infoArr[indexPath.section];
		MallBuyTogetherModel *model = [[MallBuyTogetherModel alloc] init];
		[model setValuesForKeysWithDictionary:sup.goodss[indexPath.row]];
		
		MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
		detailVC.goodId = model.goods_id;
		detailVC.isBuytogetherMode = @"1";
		[self.navigationController pushViewController:detailVC animated:YES];
	}
	else
	{
		FullGate *sup = self.infoArr[indexPath.section];
		Goods *model = [[Goods alloc] init];
		[model setValuesForKeysWithDictionary:sup.goodss[indexPath.row]];
		//Goods *model = self.infoArr[indexPath.row];
		
		MallDetailViewController *detailVC = [[MallDetailViewController alloc] init];
		detailVC.goodId = model.goods_id;
		detailVC.isBuytogetherMode = model.is_ecbuy;
		[self.navigationController pushViewController:detailVC animated:YES];
	}
}
//创建头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {
    /*
    UICollectionReusableView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"UICollectionViewHeader" forIndexPath:indexPath];
    [headView addSubview:_carouselView];
    [headView addSubview:_recommendBtn];
    headView.backgroundColor = kWhiteColor;
    
    return headView;
	 */
	NSString *reuseIdentifier;
	if ([kind isEqualToString:UICollectionElementKindSectionHeader])
	{ // header
		reuseIdentifier = @"HomeCollectionViewHeaderView";
	}
	HomeCollectionViewHeaderView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind
																			withReuseIdentifier:reuseIdentifier
																				   forIndexPath:indexPath];
	//移除第一个头视图里的广告图，不然会重复显示
	if (view.subviews.count > 3) {
		[view.subviews.lastObject removeFromSuperview];
	}
	
	if ([kind isEqualToString:UICollectionElementKindSectionHeader])
	{
		if (indexPath.section == 0) {
			view.isFirst = YES;
			[view addSubview:_carouselView];
		}
		else {
			view.isFirst = NO;
		}
		if (self.infoArr.count) {
			FullGate *model = self.infoArr[indexPath.section];
			view.title.text = [NSString stringWithFormat:@"  %@", model.cate_name];
			
			[view.moreV addActionWithblock:^{
				MallListViewController *listVC = [[MallListViewController alloc] init];
				listVC.type = 1;
				listVC.titleName = model.cate_name;
				listVC.cate_id = [NSString stringWithFormat:@"%ld", model.cate_id];
				[self.navigationController pushViewController:listVC animated:YES];
			}];
		}
	}
	return view;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
	
	if (section == 0) {
		return CGSizeMake(SCREEN_WIDTH, SW(5)*2+44);
	}
	return CGSizeMake(SCREEN_WIDTH, 44);
}


#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _collectionView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        //weakSelf.page++;
        [weakSelf GETMallsGoods];
    }];
    
}

#pragma mark ===========响应方法==========
- (void)GETMallsGoods {
    
    NSDictionary *param = @{@"per_page":@"6", @"page":[NSString stringWithFormat:@"%ld", self.page]};
	//NSDictionary *param = @{@"per_page":@"6"};
    
    [[NetworkTool sharedTool] requestWithName:@"获取商城首页商品" URLString:APIMallsIndex parameters:param method:@"GET" callBack:^(id responseObject) {
        
        NSArray *arr = responseObject[@"data"];
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
		
		/*
        for (NSDictionary *arr1 in arr)
		{
			//第一层拿到大分类比如说“汽车”，然后第二层拿到子分类比如说"SUV"
			if (![arr1 isEqual:[NSNull null]]) {
				for (NSDictionary *dic in arr1[@"children"]) {
					
					FullGate *model = [[FullGate alloc] init];
					[model setValuesForKeysWithDictionary:dic];
					[self.infoArr addObject:model];
				}
			}
		}
		if (self.page == 1) {
			FullGate *last = self.infoArr.lastObject;
			[self.infoArr removeLastObject];
			[self.infoArr insertObject:last atIndex:0];
		}
		 */
		
		for (NSDictionary *dic in arr)
		{
			FullGate *model = [[FullGate alloc] init];
			[model setValuesForKeysWithDictionary:dic];
			[self.infoArr addObject:model];
		}

        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
			[_collectionView.mj_header endRefreshing];
            [_collectionView.mj_footer endRefreshing];
            [_collectionView reloadData];
        });
    }];
}

// 获取广告
- (void)GETAds {
    
    [AdsServer GETAds:@{@"board":@"app_mall"} xrView:_carouselView];
    
}

// 返回
- (void)nearbyShopBtnClick:(UIButton *)sender {
	NearbyShopViewController *vc = [[NearbyShopViewController alloc] init];
	[self.navigationController pushViewController:vc animated:YES];
}
// 进入商品分类
- (void)speciesClick:(UIButton *)sender {
	[self.navigationController pushViewController:[[MallClassificationViewController alloc] init] animated:YES];
   //[self.navigationController pushViewController:[[MallClassViewController alloc] init] animated:YES];
}
// 进入购物车列表
- (void)cartClick:(UIButton *)sender {
    //MallShopCartViewController *cartVC = [[MallShopCartViewController alloc] init];
    //[self.navigationController pushViewController:cartVC animated:YES];
    MKJShoppingCartViewController *shop = [[MKJShoppingCartViewController alloc] init];
    [self.navigationController pushViewController:shop animated:YES];
}

// 商品搜索
- (void)searchClicK:(id)sender {
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.type = 3;
    [self.navigationController pushViewController:searchVC animated:YES];
}


// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
